package org.cancer.activemq;

import java.io.IOException;
 
import javax.jms.Connection; 
import javax.jms.ConnectionFactory; 
import javax.jms.Destination; 
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer; 
import javax.jms.MessageListener;
import javax.jms.Session; 
import javax.jms.TextMessage; 

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.activemq.ActiveMQConnection; 
import org.apache.activemq.ActiveMQConnectionFactory; 
 
public class JmsReceiverServlet extends HttpServlet {
 
    private ConnectionFactory connectionFactory = null;
    private Connection connection = null;
    private Session session = null;
    private MessageConsumer consumer = null;
    private Destination destination = null;
     
    public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("1111111111111111111111");
		request.setCharacterEncoding("utf-8");
		receive();
		request.getRequestDispatcher("/index.jsp").forward(request,response);
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}
     
    public void receive(){
        connectionFactory = new ActiveMQConnectionFactory(
                ActiveMQConnection.DEFAULT_USER,
                ActiveMQConnection.DEFAULT_PASSWORD,"tcp://localhost:61616");
        try{
            connection = connectionFactory.createConnection();
            connection.start();
            session = connection.createSession(Boolean.TRUE.booleanValue(), 
                    Session.AUTO_ACKNOWLEDGE);
            destination = session.createQueue("xkey");
            consumer = session.createConsumer(destination);
            consumer.setMessageListener(new MessageListener(){
 
                public void onMessage(Message msg) {
                    TextMessage message = (TextMessage)msg;
                    try{
                        System.out.println("Receiver " + message.getText()); 
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                }
            });
            /**while (true) { 
                TextMessage message = (TextMessage) consumer.receive(1000); 
                if (null != message) { 
                    System.out.println("Receiver " + message.getText()); 
                } else { 
                    break; 
                } 
            }  */
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try {
                connection.close();
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
    }
}